package com.community.zhihuishequ.view.monitor;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.AppCompatImageButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.community.zhihuishequ.R;
import com.community.zhihuishequ.third.HikInterface;
import com.community.zhihuishequ.third.hik.widget.CustomSurfaceView;
import com.community.zhihuishequ.view.base.BaseActivity;
import com.community.zhihuishequ.widget.GridViewInRecyclerView;
import com.community.zhihuishequ.widget.recyclertreeview.TreeNode;
import com.community.zhihuishequ.widget.recyclertreeview.TreeViewBinder;
import com.hikvision.sdk.VMSNetSDK;
import com.hikvision.sdk.consts.SDKConstant;
import com.hikvision.sdk.net.bean.CustomRect;
import com.hikvision.sdk.net.bean.SubResourceNodeBean;
import com.hikvision.sdk.net.business.OnVMSNetSDKBusiness;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 营区监控
 */
public class MonitorActivity extends BaseActivity {

    private Toolbar topToolBar;
    private TextView tvTitle;

    // 视频部分
    private CustomSurfaceView svMainPreview, svMainPreview2, svMainPreview3, svMainPreview4, svMainPreviewOne;
    private RelativeLayout loSurfaceView1, loSurfaceView2, loSurfaceView3, loSurfaceView4, loSurfaceViewOne;
    //当前选中的视频框
    private CustomSurfaceView currentPreview;
    //当前视频框的位置
    private int currentPreviewIndex;
    private List<RelativeLayout> loSurfaceViewList;
    private List<CustomSurfaceView> svMainPreviewList;
    private TextView tvSurfaceTitle, tvSurfaceTitle2, tvSurfaceTitle3, tvSurfaceTitle4, tvSurfaceTitleOne;
    private List<TextView> tvSurfaceTitleList;
    private ImageView btnAdd, btnAdd2, btnAdd3, btnAdd4, btnAddOne;
    private List<ImageView> btnAddList;
    private List<SubResourceNodeBean> curPlayingNodeList;
    private TextView tvSurfaceLoading, tvSurfaceLoading2, tvSurfaceLoading3, tvSurfaceLoading4, tvSurfaceLoadingOne;
    private List<TextView> tvSurfaceLoadingList;

    // 底部三个按钮，截屏，声音，全屏
    private AppCompatImageButton btnScreenshot;
    private AppCompatImageButton btnSound;
    private AppCompatImageButton btnZoom;

    // 点击出现选择点的按钮
    private LinearLayout loSelectPointSwitcher;

    // 下拉列表
    private RecyclerView rvSelectPointTree;
    //    private TreeViewAdapter selectPointAdapter;
    private List<TreeNode> selectPointDataList = new ArrayList<>();
    private MonitorParentAdapter monitorParentAdapter;
    private List<MonitorSubResourceNodeBean> subResourceNodeBeanList = new ArrayList<>();
    private Integer position;

    // 高清 标清 低清
    private int videoQuality;
    private AppCompatCheckBox btnHd;
    private AppCompatCheckBox btnSd;
    private AppCompatCheckBox btnLd;


    private Map<CustomSurfaceView, Integer> windowsIdMap = new HashMap<>();

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"
    };
    private List<Integer> qualityList;

    private TextView btnOne, btnFour;
    private LinearLayout surfaceViewTop, surfaceViewBottom;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitor);
        initView();
        init();
        initListener();
        MonitorController.getInstance().login();


//        fillTestData();
//        selectPointAdapter.refresh(selectPointDataList);
//        MonitorController.getInstance().doStartLive();
//        fillTestData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        for (int i = 0; i < curPlayingNodeList.size(); i++) {
            if (svMainPreviewList.get(i).isSurfaceCreated() && curPlayingNodeList.get(i) != null) {
                startLive(curPlayingNodeList.get(i), videoQuality, svMainPreviewList.get(i), i);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
        stopLive();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        MonitorController.getInstance().unInit();
    }

    private synchronized int getWindowId(CustomSurfaceView surfaceView) {
        Integer winId = windowsIdMap.get(surfaceView);
        if (winId == null) {
            winId = windowsIdMap.size() + 1;
            windowsIdMap.put(surfaceView, winId);
        }
        return winId;
    }

    private void initView() {
        topToolBar = findViewById(R.id.toolBar);
        tvTitle = findViewById(R.id.txvTitle);
        btnScreenshot = findViewById(R.id.btn_screenshot);
        btnSound = findViewById(R.id.btn_sound);
        btnZoom = findViewById(R.id.btn_zoom);
        loSelectPointSwitcher = findViewById(R.id.lo_select_point);
        rvSelectPointTree = findViewById(R.id.rv_select_point);

        svMainPreview = findViewById(R.id.surfaceView1);
        svMainPreview2 = findViewById(R.id.surfaceView2);
        svMainPreview3 = findViewById(R.id.surfaceView3);
        svMainPreview4 = findViewById(R.id.surfaceView4);
        svMainPreviewOne = findViewById(R.id.surfaceView_one);

        tvSurfaceTitle = findViewById(R.id.tv_surface_title1);
        tvSurfaceTitle2 = findViewById(R.id.tv_surface_title2);
        tvSurfaceTitle3 = findViewById(R.id.tv_surface_title3);
        tvSurfaceTitle4 = findViewById(R.id.tv_surface_title4);
        tvSurfaceTitleOne = findViewById(R.id.tv_surface_title_one);

        btnAdd = findViewById(R.id.btn_add1);
        btnAdd2 = findViewById(R.id.btn_add2);
        btnAdd3 = findViewById(R.id.btn_add3);
        btnAdd4 = findViewById(R.id.btn_add4);
        btnAddOne = findViewById(R.id.btn_add_one);


        tvSurfaceLoading = findViewById(R.id.tv_surface_loading1);
        tvSurfaceLoading2 = findViewById(R.id.tv_surface_loading2);
        tvSurfaceLoading3 = findViewById(R.id.tv_surface_loading3);
        tvSurfaceLoading4 = findViewById(R.id.tv_surface_loading4);
        tvSurfaceLoadingOne = findViewById(R.id.tv_surface_loading_one);

        btnHd = findViewById(R.id.btn_hd);
        btnSd = findViewById(R.id.btn_sd);
        btnLd = findViewById(R.id.btn_ld);

        btnOne = findViewById(R.id.btn_one);
        btnFour = findViewById(R.id.btn_four);

        surfaceViewTop = findViewById(R.id.ll_surface_view_top);
        surfaceViewBottom = findViewById(R.id.ll_surface_view_bottom);

        loSurfaceView1 = findViewById(R.id.lo_surface_view1);
        loSurfaceView2 = findViewById(R.id.lo_surface_view2);
        loSurfaceView3 = findViewById(R.id.lo_surface_view3);
        loSurfaceView4 = findViewById(R.id.lo_surface_view4);
        loSurfaceViewOne = findViewById(R.id.lo_surface_view_one);

        addFourList();
    }

    private void initList() {
        if (svMainPreviewList == null) {
            svMainPreviewList = new ArrayList<>();
        } else {
            svMainPreviewList.clear();
        }
        if (tvSurfaceTitleList == null) {
            tvSurfaceTitleList = new ArrayList<>();
        } else {
            tvSurfaceTitleList.clear();
        }
        if (btnAddList == null) {
            btnAddList = new ArrayList<>();
        } else {
            btnAddList.clear();
        }
        if (tvSurfaceLoadingList == null) {
            tvSurfaceLoadingList = new ArrayList<>();
        } else {
            tvSurfaceLoadingList.clear();
        }
        if (loSurfaceViewList == null) {
            loSurfaceViewList = new ArrayList<>();
        } else {
            loSurfaceViewList.clear();
        }
        if (qualityList == null) {
            qualityList = new ArrayList<>();
        } else {
            qualityList.clear();
        }
        if (curPlayingNodeList == null) {
            curPlayingNodeList = new ArrayList<>();
        } else {
            curPlayingNodeList.clear();
        }
    }

    //添加四宫格的视频控件到list中
    private void addFourList() {
        initList();
        loSurfaceViewOne.setVisibility(View.GONE);
        surfaceViewTop.setVisibility(View.VISIBLE);
        surfaceViewBottom.setVisibility(View.VISIBLE);
        svMainPreview.setVisibility(View.VISIBLE);
        svMainPreview2.setVisibility(View.VISIBLE);
        svMainPreview3.setVisibility(View.VISIBLE);
        svMainPreview4.setVisibility(View.VISIBLE);
        currentPreviewIndex = 0;
        currentPreview = svMainPreview;

        svMainPreviewList.add(svMainPreview);
        svMainPreviewList.add(svMainPreview2);
        svMainPreviewList.add(svMainPreview3);
        svMainPreviewList.add(svMainPreview4);

        tvSurfaceTitleList.add(tvSurfaceTitle);
        tvSurfaceTitleList.add(tvSurfaceTitle2);
        tvSurfaceTitleList.add(tvSurfaceTitle3);
        tvSurfaceTitleList.add(tvSurfaceTitle4);

        btnAddList.add(btnAdd);
        btnAddList.add(btnAdd2);
        btnAddList.add(btnAdd3);
        btnAddList.add(btnAdd4);

        tvSurfaceLoadingList.add(tvSurfaceLoading);
        tvSurfaceLoadingList.add(tvSurfaceLoading2);
        tvSurfaceLoadingList.add(tvSurfaceLoading3);
        tvSurfaceLoadingList.add(tvSurfaceLoading4);

        int h = getResources().getDisplayMetrics().widthPixels / 2 * 1080 / 1920;
        loSurfaceViewList.add(loSurfaceView1);
        ViewGroup.LayoutParams lp = loSurfaceView1.getLayoutParams();
        lp.height = h;
        loSurfaceView1.setLayoutParams(lp);
        configSurface(svMainPreview);

        loSurfaceViewList.add(loSurfaceView2);
        ViewGroup.LayoutParams lp2 = loSurfaceView2.getLayoutParams();
        lp2.height = h;
        loSurfaceView2.setLayoutParams(lp2);
        configSurface(svMainPreview2);

        loSurfaceViewList.add(loSurfaceView3);
        ViewGroup.LayoutParams lp3 = loSurfaceView3.getLayoutParams();
        lp3.height = h;
        loSurfaceView3.setLayoutParams(lp3);
        configSurface(svMainPreview3);

        loSurfaceViewList.add(loSurfaceView4);
        ViewGroup.LayoutParams lp4 = loSurfaceView4.getLayoutParams();
        lp4.height = h;
        loSurfaceView4.setLayoutParams(lp4);
        configSurface(svMainPreview4);

        for (int i = 0; i < 4; i++) {
            qualityList.add(HikInterface.SD);
            curPlayingNodeList.add(null);
        }
    }

    //添加只有一个的视频控件到list中
    private void addOneList() {
        initList();
        loSurfaceViewOne.setVisibility(View.VISIBLE);
        surfaceViewTop.setVisibility(View.GONE);
        surfaceViewBottom.setVisibility(View.GONE);
        svMainPreview.setVisibility(View.GONE);
        svMainPreview2.setVisibility(View.GONE);
        svMainPreview3.setVisibility(View.GONE);
        svMainPreview4.setVisibility(View.GONE);
        currentPreviewIndex = 0;
        currentPreview = svMainPreviewOne;

        svMainPreviewList.add(svMainPreviewOne);
        tvSurfaceTitleList.add(tvSurfaceTitleOne);
        btnAddList.add(btnAddOne);
        tvSurfaceLoadingList.add(tvSurfaceLoadingOne);

        int hBig = getResources().getDisplayMetrics().widthPixels * 1080 / 1920;
        loSurfaceViewList.add(loSurfaceViewOne);
        ViewGroup.LayoutParams lpBig = loSurfaceViewOne.getLayoutParams();
        lpBig.height = hBig;
        loSurfaceViewOne.setLayoutParams(lpBig);
        configSurface(svMainPreviewOne);

        for (int i = 0; i < 1; i++) {
            qualityList.add(HikInterface.SD);
            curPlayingNodeList.add(null);
        }
    }

    private void verifyStoragePermissions() {
        try {
            int permission = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            } else {
                screenShot();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void screenShot() {
        if (curPlayingNodeList.get(currentPreviewIndex) == null) {
            EventBus.getDefault().post(new MonitorToastEvent("视频还没播放，请您选择查看摄像机！"));
            return;
        }
        MonitorController.getInstance().screenshot(getWindowId(currentPreview));
    }

    private void setLoSurfaceViewBackgroud(int index) {
        if (loSurfaceViewList.size() > index && svMainPreviewList.size() > index) {
            for (RelativeLayout item : loSurfaceViewList) {
                if (item == loSurfaceViewList.get(index)) {
                    item.setBackground(getResources().getDrawable(R.drawable.bg_round_red));
                    currentPreview = svMainPreviewList.get(index);
                    currentPreviewIndex = index;
                } else {
                    item.setBackground(null);
                }
            }
        }
    }

    private void setQuality(int index) {
        Integer item = qualityList.get(index);
        if (item == HikInterface.HD) {
            btnHd.setChecked(true);
        } else {
            btnHd.setChecked(false);
        }
        if (item == HikInterface.LD) {
            btnLd.setChecked(true);
        } else {
            btnLd.setChecked(false);
        }
        if (item == HikInterface.SD) {
            btnSd.setChecked(true);
        } else {
            btnSd.setChecked(false);
        }
    }

    private void stopLive() {
        for (int i = 0; i < svMainPreviewList.size(); i++) {
            MonitorController.getInstance().doStopLive(getWindowId(svMainPreviewList.get(i)));
            tvSurfaceTitleList.get(i).setVisibility(View.GONE);
            tvSurfaceLoadingList.get(i).setVisibility(View.GONE);
            btnAddList.get(i).setVisibility(View.VISIBLE);
        }
    }

    private void initListener() {

        svMainPreview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                setLoSurfaceViewBackgroud(0);
                setQuality(0);
                return true;
            }
        });

        svMainPreview2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                setLoSurfaceViewBackgroud(1);
                setQuality(1);
                return true;
            }
        });

        svMainPreview3.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                setLoSurfaceViewBackgroud(2);
                setQuality(2);
                return true;
            }
        });

        svMainPreview4.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                setLoSurfaceViewBackgroud(3);
                setQuality(3);
                return true;
            }
        });

        // 截屏按钮
        btnScreenshot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                verifyStoragePermissions();
            }
        });
        // 声音按钮（静音）
        btnSound.setTag(true);
        btnSound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (curPlayingNodeList.get(currentPreviewIndex) == null) {
                    EventBus.getDefault().post(new MonitorToastEvent("视频还没播放，请您选择查看摄像机！"));
                    return;
                }
                if ((boolean) btnSound.getTag()) {
                    btnSound.setImageResource(R.drawable.ic_monitor_sound);
                    MonitorController.getInstance().mute(getWindowId(currentPreview), false);
                } else {
                    btnSound.setImageResource(R.drawable.ic_monitor_sound_off);
                    MonitorController.getInstance().mute(getWindowId(currentPreview), true);
                }
                btnSound.setTag(!((boolean) btnSound.getTag()));
            }
        });
        // 全屏按钮
        btnZoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (curPlayingNodeList.get(currentPreviewIndex) == null) {
                    EventBus.getDefault().post(new MonitorToastEvent("视频还没播放，请您选择查看摄像机！"));
                    return;
                }
                MonitorController.getInstance().doStopLive(getWindowId(currentPreview));
                Intent i = new Intent(MonitorActivity.this, MonitorVideoActivity.class);
                i.putExtra(MonitorVideoActivity.EXTRA_NODE, curPlayingNodeList.get(currentPreviewIndex));
                i.putExtra(MonitorVideoActivity.EXTRA_VIDEO_QUALITY, videoQuality);
                i.putExtra(MonitorVideoActivity.EXTRA_PID, curPlayingNodeList.get(currentPreviewIndex).getPid());
                startActivityForResult(i, 0);
            }
        });

        // surface 中间的加号
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setLoSurfaceViewBackgroud(0);
                showSelectPointList(true);
            }
        });

        btnAdd2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setLoSurfaceViewBackgroud(1);
                showSelectPointList(true);
            }
        });

        btnAdd3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setLoSurfaceViewBackgroud(2);
                showSelectPointList(true);
            }
        });

        btnAdd4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setLoSurfaceViewBackgroud(3);
                showSelectPointList(true);
            }
        });

        btnAddOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentPreviewIndex = 0;
                currentPreview = svMainPreviewOne;
                showSelectPointList(true);
            }
        });

        // 下拉列表
        loSelectPointSwitcher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showSelectPointList(rvSelectPointTree.getVisibility() == View.GONE);
            }
        });
//        selectPointAdapter.setOnTreeNodeListener(new TreeViewAdapter.OnTreeNodeListener() {
//            @Override
//            public boolean onClick(TreeNode node, RecyclerView.ViewHolder holder) {
//                if (node.isLeaf()) {
//                    if (node.getContent() instanceof SubWarp) {
//                        SubWarp subWarp = (SubWarp) node.getContent();
//                        startLive(subWarp.getNode(), videoQuality);
//                    } else if (node.getContent() instanceof ParentWarp) {
//                        SubResourceNodeBean hikNode = ((ParentWarp) node.getContent()).node;
//                        MonitorController.getInstance().getSubResourceList(node, hikNode.getNodeType(), hikNode.getId());
//                    }
//                }
//                return false;
//            }
//
//            @Override
//            public void onToggle(boolean isExpand, RecyclerView.ViewHolder holder) {
//            }
//        });
        // 切换1个视频模式

        View.OnClickListener switchVideoQuality = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.btn_hd:
                        videoQuality = HikInterface.HD;
                        break;
                    case R.id.btn_sd:
                        videoQuality = HikInterface.SD;
                        break;
                    case R.id.btn_ld:
                        videoQuality = HikInterface.LD;
                        break;
                }

                btnHd.setChecked(false);
                btnSd.setChecked(false);
                btnLd.setChecked(false);
                ((AppCompatCheckBox) view).setChecked(true);
                if (curPlayingNodeList.get(currentPreviewIndex) != null) {
                    MonitorController.getInstance().doStopLive(getWindowId(currentPreview));
                    startLive(curPlayingNodeList.get(currentPreviewIndex), videoQuality, currentPreview, currentPreviewIndex);
                }
                qualityList.set(currentPreviewIndex, videoQuality);
            }
        };
        btnHd.setOnClickListener(switchVideoQuality);
        btnSd.setOnClickListener(switchVideoQuality);
        btnLd.setOnClickListener(switchVideoQuality);

        btnOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopLive();
                addOneList();
            }
        });

        btnFour.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopLive();
                addFourList();
            }
        });
    }

    private void init() {
        setSupportActionBar(topToolBar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        if (tvTitle != null) {
            tvTitle.setText(getTitle());
        }

        monitorParentAdapter = new MonitorParentAdapter(R.layout.item_monitor_parent, selectPointDataList);
        rvSelectPointTree.setLayoutManager(new LinearLayoutManager(this));
        rvSelectPointTree.setAdapter(monitorParentAdapter);

        videoQuality = HikInterface.SD;
        btnSd.setChecked(true);

        setLoSurfaceViewBackgroud(0);
    }

    private void configSurface(final CustomSurfaceView sv) {
        sv.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                sv.setSurfaceCreated(true);
            }

            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

            }
        });
        // 视频放大缩小控制
        sv.setOnZoomListener(new CustomSurfaceView.OnZoomListener() {
            @Override
            public void onZoomChange(CustomRect original, CustomRect current) {
                VMSNetSDK.getInstance().zoomLiveOpt(getWindowId(sv), true, original, current);
            }
        });
    }

    private void showSelectPointList(boolean show) {
        if (show) {
            rvSelectPointTree.setVisibility(View.VISIBLE);
            Animation anim = new AlphaAnimation(0.0f, 1.0f);
            anim.setDuration(150);
            rvSelectPointTree.startAnimation(anim);
            monitorParentAdapter.notifyDataSetChanged();
        } else {
            rvSelectPointTree.setVisibility(View.GONE);
            Animation anim = new AlphaAnimation(1.0f, 0.0f);
            anim.setDuration(150);
            rvSelectPointTree.startAnimation(anim);
        }
    }

    private void startLive(final SubResourceNodeBean node, int videoQuality, CustomSurfaceView view, final int index) {
        curPlayingNodeList.set(index, node);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvSurfaceTitleList.get(index).setText(node.getName());
                btnAddList.get(index).setVisibility(View.GONE);
                tvSurfaceLoadingList.get(index).setVisibility(View.VISIBLE);
            }
        });
        MonitorController.getInstance().doStartLive(getWindowId(view), node, view, videoQuality, new OnVMSNetSDKBusiness() {
            @Override
            public void onFailure() {
                super.onFailure();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvSurfaceLoadingList.get(index).setVisibility(View.GONE);
                    }
                });
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvSurfaceLoadingList.get(index).setVisibility(View.GONE);
                    }
                });
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onToastEvent(MonitorToastEvent event) {
        showToast(event.getMsg());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateListEvent(MonitorListEvent event) {
        TreeNode uiNode = event.getUiNode();
        if (uiNode == null) {
            List<SubResourceNodeBean> nodeList = event.getNodeList();
            for (SubResourceNodeBean node : nodeList) {
                if (node.getNodeType() == SDKConstant.NodeType.TYPE_CAMERA_OR_DOOR) {
                    selectPointDataList.add(new TreeNode<>(new SubWarp(node)));

//                    for (TreeNode loopNode : selectPointDataList) {
//                        if (loopNode.getContent() instanceof SubWarp) {
//                            SubWarp warp = (SubWarp) loopNode.getContent();
//                            warp.getNode().getId() ==
//                        }
//                    }
                } else {
                    TreeNode<ParentWarp> parentNode = new TreeNode<>(new ParentWarp(node));
                    //parentNode.getContent().setNumber("0");
                    selectPointDataList.add(parentNode);
                    SubResourceNodeBean hikNode = parentNode.getContent().node;
                    MonitorController.getInstance().getSubResourceList(parentNode, hikNode.getNodeType(), hikNode.getId());
                }
            }
        } else {
            List<SubResourceNodeBean> nodeList = event.getNodeList();
            for (SubResourceNodeBean node : nodeList) {
                if (node.getNodeType() == SDKConstant.NodeType.TYPE_CAMERA_OR_DOOR) {
                    uiNode.addChild(new TreeNode<>(new SubWarp(node)));
                } else {
                    TreeNode<ParentWarp> addNode = new TreeNode<>(new ParentWarp(node));
                    uiNode.addChild(addNode);
                    MonitorController.getInstance().getSubResourceList(addNode, node.getNodeType(), node.getId());
                }
            }
            uiNode.expand();
        }
        monitorParentAdapter.notifyDataSetChanged();
    }

    public class ParentWarp {
        private SubResourceNodeBean node;
        private String number;

        public ParentWarp(SubResourceNodeBean node) {
            this.node = node;
        }

        public SubResourceNodeBean getNode() {
            return node;
        }

        public String getNumber() {
            return number;
        }

        public void setNumber(String number) {
            this.number = number;
        }
    }

    public class SubWarp {
        private SubResourceNodeBean node;

        public SubWarp(SubResourceNodeBean node) {
            this.node = node;
        }

        public SubResourceNodeBean getNode() {
            return node;
        }
    }

    public class ParentWarpBinder extends TreeViewBinder<ParentWarpBinder.ViewHolder> {
        @Override
        public ViewHolder provideViewHolder(View itemView) {
            return new ViewHolder(itemView);
        }

        @Override
        public void bindView(ViewHolder holder, int position, TreeNode node) {
            ParentWarp nodeWarp = (ParentWarp) node.getContent();
            holder.ctvName.setText(nodeWarp.getNode().getName());
            holder.tvNumber.setText(nodeWarp.getNumber());
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_monitor_select_point_parent;
        }

        public class ViewHolder extends TreeViewBinder.ViewHolder {
            public CheckedTextView ctvName;
            public TextView tvNumber;

            public ViewHolder(View rootView) {
                super(rootView);
                this.ctvName = rootView.findViewById(R.id.ctv_name);
                this.tvNumber = rootView.findViewById(R.id.tv_number);
            }

        }
    }

    public class SubWarpBinder extends TreeViewBinder<SubWarpBinder.ViewHolder> {
        @Override
        public ViewHolder provideViewHolder(View itemView) {
            return new ViewHolder(itemView);
        }

        @Override
        public void bindView(ViewHolder holder, int position, final TreeNode node) {
            SubWarp nodeWarp = (SubWarp) node.getContent();
            holder.cbName.setText(nodeWarp.getNode().getName());
            holder.cbName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showSelectPointList(false);
                    startLive(((SubWarp) node.getContent()).getNode(), videoQuality, currentPreview, currentPreviewIndex);
                }
            });
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_monitor_select_point_sub;
        }

        public class ViewHolder extends TreeViewBinder.ViewHolder {
            public AppCompatCheckBox cbName;

            public ViewHolder(View rootView) {
                super(rootView);
                this.cbName = rootView.findViewById(R.id.cb_name);
            }

        }
    }

    private void fillTestData() {
        SubResourceNodeBean dirNode = new SubResourceNodeBean();
        dirNode.setId(1);
        dirNode.setName("南面");
        SubResourceNodeBean subNode1 = new SubResourceNodeBean();
        subNode1.setId(2);
        subNode1.setName("南面1楼");
        subNode1.setNodeType(SDKConstant.NodeType.TYPE_CAMERA_OR_DOOR);
        SubResourceNodeBean subNode2 = new SubResourceNodeBean();
        subNode2.setId(3);
        subNode2.setName("南面2楼");
        subNode2.setNodeType(SDKConstant.NodeType.TYPE_CAMERA_OR_DOOR);
        SubResourceNodeBean subNode3 = new SubResourceNodeBean();
        subNode3.setId(4);
        subNode3.setName("南面3楼");
        subNode3.setNodeType(SDKConstant.NodeType.TYPE_CAMERA_OR_DOOR);

        TreeNode<ParentWarp> uiDirNode = new TreeNode<>(new ParentWarp(dirNode));
        uiDirNode.addChild(new TreeNode<>(new SubWarp(subNode1)));
        uiDirNode.addChild(new TreeNode<>(new SubWarp(subNode2)));
        uiDirNode.addChild(new TreeNode<>(new SubWarp(subNode3)));

//        selectPointDataList.add(uiDirNode);
    }

    private class MonitorParentAdapter extends BaseQuickAdapter<TreeNode, BaseViewHolder> {

        public MonitorParentAdapter(int layoutResId, @Nullable List<TreeNode> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, TreeNode subResourceNodeBean) {
            ParentWarp parentWarp = (ParentWarp) subResourceNodeBean.getContent();
            baseViewHolder.setText(R.id.tv_parent_title, parentWarp.getNode().getName());
            if (subResourceNodeBean.getChildList() != null) {
                GridViewInRecyclerView gv = baseViewHolder.getView(R.id.gv_parent);
                MonitorChildrenAdapter adapter = new MonitorChildrenAdapter(subResourceNodeBean.getChildList());
                gv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        }
    }

    private class MonitorChildrenAdapter extends BaseAdapter {

        private List<TreeNode> dataList;

        public MonitorChildrenAdapter(List<TreeNode> dataList) {
            this.dataList = dataList;
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_monitor_children, null);
                if (dataList.get(position).getContent() instanceof SubWarp) {
                    final SubWarp subWarp = (SubWarp) dataList.get(position).getContent();
                    TextView tvTitle = convertView.findViewById(R.id.tv_children_title);
                    tvTitle.setText(subWarp.getNode().getName());
                    if (tvSurfaceTitle.getText().toString().equals(subWarp.getNode().getName())) {
                        tvTitle.setTextColor(getResources().getColor(R.color.white));
                        RelativeLayout item = convertView.findViewById(R.id.rl_item);
                        item.setBackground(getResources().getDrawable(R.drawable.bg_round_blue));
                    } else {
                        tvTitle.setTextColor(getResources().getColor(R.color.textBlack));
                        RelativeLayout item = convertView.findViewById(R.id.rl_item);
                        item.setBackground(getResources().getDrawable(R.drawable.bg_round_blue));
                    }
                    convertView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showSelectPointList(false);
                            startLive(subWarp.getNode(), videoQuality, currentPreview, currentPreviewIndex);
                        }
                    });
                }
            }
            return convertView;
        }

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (rvSelectPointTree.getVisibility() == View.VISIBLE) {
            rvSelectPointTree.setVisibility(View.GONE);
            Animation anim = new AlphaAnimation(1.0f, 0.0f);
            anim.setDuration(150);
            rvSelectPointTree.startAnimation(anim);
        } else {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (rvSelectPointTree.getVisibility() == View.VISIBLE) {
            rvSelectPointTree.setVisibility(View.GONE);
            Animation anim = new AlphaAnimation(1.0f, 0.0f);
            anim.setDuration(150);
            rvSelectPointTree.startAnimation(anim);
        } else {
            finish();
        }
    }
}
